package com.tiyende.credit.loop.ui.presenter

import com.lib.common.http.callback.StringCallback
import com.lib.common.http.model.Progress
import com.lib.common.http.model.Response
import com.lib.common.http.request.base.Request
import com.tiyende.credit.loop.common.CommonPresenter
import com.tiyende.credit.loop.request.HttpHelper
import com.tiyende.credit.loop.ui.contract.IViewContract
import com.tiyende.credit.loop.utils.log.TiyendeLogger
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/20 18:45
 * @Annotation：上传图片
 */
class TiyendeImageUploadPresenter(private val iView: IViewContract.ITiyendeImageUploadView): CommonPresenter(iView) {

    /**
     * 上传图片
     */
    fun submitUploadImageAction(imgPath: String){
        HttpHelper.upload(imgPath,object : StringCallback(){
            override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                super.onStart(request)
                TiyendeLogger.e("upload start")
            }
            override fun onSuccess(response: Response<String>?) {
                TiyendeLogger.e("upload success ："+response?.body())
                if (response?.code() == 200){
                    iView.hiddenTiyendeLoading()
                    val data = JSONObject(response.body())
                    when(data.optInt("code")){
                        0 -> {//成功
                            val obj = data.optJSONObject("obj")
                            obj?.let {
                                val imgUrl = it.optString("url")
                                iView.showTiyendeImageUploadSuccess(imgPath,imgUrl)
                            }
                        }
                        else -> {
                            val msg = data.optString("msg")
                            iView.showTiyendeToast(msg)
                        }
                    }
                } else {
                    iView.showTiyendeToast(response?.message())
                }
            }
            override fun onError(response: Response<String>?) {
                TiyendeLogger.e("upload error，code： ${response?.code()} , message：${response?.message()}")
                iView.showTiyendeToast(response?.message())
            }
            override fun uploadProgress(progress: Progress) {
                TiyendeLogger.e("uploadProgress: $progress")
                TiyendeLogger.e("uploadProgress，total: ${progress.totalSize}")
                TiyendeLogger.e("uploadProgress，progress: ${progress.currentSize}")
            }
            override fun onFinish() {
                iView.hiddenTiyendeLoading()
            }
        })
    }
}